package de.silvalauinger.objectclassmapper.common;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import java.lang.annotation.Annotation;

public final class Annotations {

    //<editor-fold defaultstate="collapsed" desc="Constructors">
    private Annotations() {
    }
    //</editor-fold>

    /**
     * Tries to get an annotation from an annotated class. Throws
     * {@link IllegalArgumentException} if {@code annotationType} is absent.
     *
     * @param <TAnnotationType> Annotation type of the annotation to get.
     * @param annotatedClass {@link Class} to get the annotation from.
     * @param annotationType Type of the annotation to get.
     * @return The annotation if present.
     * @throws IllegalArgumentException If {@code annotationType} is absent.
     */
    public static <TAnnotationType extends Annotation> TAnnotationType tryGetAnnotation(final Class<?> annotatedClass, final Class<TAnnotationType> annotationType) {
        checkNotNull(annotatedClass);
        checkNotNull(annotationType);

        final TAnnotationType annotation = annotatedClass.getAnnotation(annotationType);
        if (annotation == null) {
            throw new IllegalArgumentException(format("%s has no %s annotation.", annotatedClass.getCanonicalName(), annotationType.getCanonicalName()));
        }

        return annotation;
    }
}
